package com.zzedu.framework.web.service.impl;

import com.zzedu.common.constant.Constants;
import com.zzedu.common.constant.LoginConstants;
import com.zzedu.common.constant.UserConstants;
import com.zzedu.common.core.domain.entity.SysUser;
import com.zzedu.common.enums.CommonEnums;
import com.zzedu.common.exception.user.CaptchaException;
import com.zzedu.common.exception.user.UserBlockedException;
import com.zzedu.common.exception.user.UserNotExistsException;
import com.zzedu.common.exception.user.UserPasswordNotMatchException;
import com.zzedu.common.utils.MessageUtils;
import com.zzedu.common.utils.ServletUtils;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.framework.manager.factory.AsyncFactory;
import com.zzedu.framework.web.domain.LoginForm;
import com.zzedu.framework.web.service.SysLoginService;
import com.zzedu.system.service.ISysRoleService;
import com.zzedu.system.service.ISysUserRoleService;
import com.zzedu.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 登录校验方法
 *
 * @author smarthome
 */
@Component
public class SysLoginServiceImpl implements SysLoginService {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService sysRoleService;
    /**
     * 登录参数
     *
     * @param loginForm
     * @return
     */
    public SysUser login(LoginForm loginForm) {
        // 验证码校验
        if (LoginConstants.CAPTCHA_ERROR.equals(ServletUtils.getRequest().getAttribute(LoginConstants.CURRENT_CAPTCHA))) {
            AsyncFactory.recordLogininfor(loginForm.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(loginForm.getUsername()) || StringUtils.isEmpty(loginForm.getPassword())) {
            AsyncFactory.recordLogininfor(loginForm.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("not.null"));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (loginForm.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
                || loginForm.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncFactory.recordLogininfor(loginForm.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"));
            throw new UserPasswordNotMatchException();
        }

        // 用户名不在指定范围内 错误
        if (loginForm.getUsername().length() < UserConstants.USERNAME_MIN_LENGTH
                || loginForm.getUsername().length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncFactory.recordLogininfor(loginForm.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"));
            throw new UserPasswordNotMatchException();
        }

        // 查询用户信息
        SysUser user = userService.selectUserByUserName(loginForm.getUsername(), loginForm.getUserTypeEnumns());
        if (user == null) {
            AsyncFactory.recordLogininfor(loginForm.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.not.exists"));
            throw new UserNotExistsException();
        }

        if (CommonEnums.NO == CommonEnums.getCode(user.getStatus())) {
            AsyncFactory.recordLogininfor(loginForm.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.blocked"));
            throw new UserBlockedException();
        }
        user.setRoles(sysRoleService.selectRolesByUserId(user.getId()));
        return user;
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setLoginIp(ServletUtils.getRequest().getRemoteAddr());
        user.setLoginDate(LocalDateTime.now());
        userService.updateById(user);
    }
}
